// *******************************************************************************************************
// # トップ
//   ・地域コンテンツの切り替え
// *******************************************************************************************************

$(function(){
	var storage = localStorage,
		STORAGE_ID = 'sp_top',
		SPEED = 200,
		$target = $('.main_cts');

	$(document).on('click', 'a.pjax', function(e) {
		e.preventDefault();
		var href = $(this).attr('href');
		$target.stop().animate({'opacity':0}, SPEED, 'easeOutQuad', function(e){
			$.pjax({
				url: href,
				container: '.main_cts',
				fragment : '.main_cts',
				timeout : 30000
			});
		});
	});
	$(document).on('pjax:end', function(){
		$target.stop().animate({'opacity':1}, SPEED, 'easeOutQuad');
        update_todofuken_links($('#tabSearch li.active'));
	});

	$('.shop, .room').each(function(i){
		$(this).find('a').on('click', function(e){
			e.preventDefault();
			onTabSearchClick(i);
			setStorage(i + 1);
			update_todofuken_links($('#tabSearch li.active'));
			
			var $menulist = $('.list_menu');
			var $menubtn = $('.btn_menu a');
			var $cover = $('#cover');
			
			$menubtn.removeClass('active');
			$menulist.slideToggle(500);
			$cover.animate( {opacity:'toggle',}, {duration:500, easing:'swing',});
			$('a').css('-webkit-tap-highlight-color','');
		});
	});
	$('#tabSearch li').each(function(i){
		$(this).find('a').on('click', function(e){
			e.preventDefault();
			onTabSearchClick(i);
			setStorage(i + 1);
			update_todofuken_links($('#tabSearch li.active'));
		});
	});

	function onTabSearchClick(n){
		$('#tabSearch li').removeClass('active');
		$('#tabSearch li').eq(n).addClass('active');
	};

	function setStorage(n){
		storage.setItem(STORAGE_ID, n);
	};

	var _default = storage.getItem(STORAGE_ID);
	if (_default) {
		onTabSearchClick(_default - 1);
	};

    function update_todofuken_links($this) {
		$('.main_cts a').each(function(index,elem) {
			var $elem = $(elem);
			console.log($elem);
            if (!$elem.hasClass('pjax')) {
				var url=$elem.attr('href');
				url = url.replace(/shop\/$/,"");
				if ($this.hasClass('right')) url+='shop/';
				$elem.attr('href',url);
            }
		});
	}
	if (location.href.match(/top\/1\/$/)) {
		onTabSearchClick(1);
		setStorage(2);
	} else if (location.href.match(/top\/0\/$/)) {
		onTabSearchClick(0);
		setStorage(1);
	}
});